﻿using System.Collections;
using WHC.Security.Common;

using WHC.Security.Entity;
using WHC.Security.IDAL;
using System;
using System.Collections.Generic;

namespace WHC.Security.BLL
{
    public class OU : BaseBLL<OUInfo>
	{
		private IOU ouDal;

		public OU() : base()
		{
			this.ouDal = (IOU) baseDal;
		}

		public void AddUser(int userID, int ouID)
		{
			if (this.OUInRole(ouID, "管理员"))
			{
				new User().EnabledExpire(userID);
			}
			this.ouDal.AddUser(userID, ouID);
		}

		private void FillNames(int pID, int currentID, int level, ref ArrayList ouNamesAndIDs)
		{
			List<OUInfo> list = this.Find("PID=" + pID);
			int iD = 0;
			foreach (OUInfo info in list)
			{
				iD = info.ID;
				if (iD != currentID)
				{
					ouNamesAndIDs.Add(new string('-', level*4) + info.Name);
					ouNamesAndIDs.Add(iD.ToString());
					this.FillNames(iD, currentID, level + 1, ref ouNamesAndIDs);
				}
			}
		}

		public ArrayList GetCanSetParent(int ouID)
		{
			ArrayList ouNamesAndIDs = new ArrayList();
			this.FillNames(-1, ouID, 0, ref ouNamesAndIDs);
			return ouNamesAndIDs;
		}

		public List<OUInfo> GetOUsByRole(int roleID)
		{
			return this.ouDal.GetOUsByRole(roleID);
		}

        public List<OUInfo> GetOUsByUser(int userID)
		{
			return this.ouDal.GetOUsByUser(userID);
		}

		public bool OUInRole(int ouID, string roleName)
		{
			bool flag = false;
			List<RoleInfo> rolesByOU = new Role().GetRolesByOU(ouID);
			foreach (RoleInfo info in rolesByOU)
			{
				if (info.Name == roleName)
				{
					flag = true;
					break;
				}
			}
			rolesByOU.Clear();
			return flag;
		}

		public void RemoveUser(int userID, int ouID)
		{
			if (this.OUInRole(ouID, "管理员"))
			{
				List<SimpleUserInfo> adminSimpleUsers = new Role().GetAdminSimpleUsers();
				if (adminSimpleUsers.Count == 1)
				{
					SimpleUserInfo info = (SimpleUserInfo) adminSimpleUsers[0];
					if (userID == info.ID)
					{
						throw new MyException("管理员角色至少需要包含一个用户！");
					}
				}
			}
			ouDal.RemoveUser(userID, ouID);
		}
	}
}